//

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/login_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/collect_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/login/user_info_model.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/encrypt_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/stem_analysis_widget.dart';
import 'package:hktk_app/widget/question/stem_answer_widget.dart';
import 'package:hktk_app/widget/question/stem_note_widget.dart';
import 'package:hktk_app/widget/question/stem_option_widget.dart';
import 'package:hktk_app/widget/question/stem_rich_text_widget.dart';
import 'package:hktk_app/widget/question/stem_text_widget.dart';
import 'package:hktk_app/widget/question/stem_title_widget.dart';

/// 自定义传递方法值
typedef QuestionInit = Future<Map<String, dynamic>> Function(
    String qId, String cid);

/// 试题、题干等相关页面
class StemPage extends StatefulWidget {
  /// 试题模式，ture-答题，false-背题
  final QuestionTypeEnum type;

  /// 试题加载数据方法
  final QuestionInit quesInit;

  /// 对应试题下标
  final int index;

  const StemPage({
    super.key,
    required this.index,
    required this.type,
    required this.quesInit,
  });

  @override
  State<StemPage> createState() => _StemPageState();
}

class _StemPageState extends State<StemPage>
    with AutomaticKeepAliveClientMixin {
  late BuildContext _context;

  /// 是否是第一次执行方法
  late bool _init;

  /// 试题相关信息
  late DtkInfoModel _dtk;

  /// 试题信息
  late QuestionDataModel _dataModel;

  /// 选中的值
  late List<String> _selectedList;

  /// 加载数据初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 监听对应广播
  late StreamSubscription<EventQuestionShowJx> _eventShowJx;

  late StreamSubscription<EventQuestionOnZTDX> _eventOnZTDX;

  late StreamSubscription<EventQuestionQk> _eventQk;

  @override
  void initState() {
    super.initState();
    debugPrint("stemPage 页面 -> initState 方法执行 ===> ${widget.index}");
    debugPrint("");
    _dtk = dataUtilComm.paperData!.dtkList[widget.index];
    _init = true;
    _selectedList = [];
    _futureInit = widget.quesInit(
      dataUtilComm.paperData!.dtkList[widget.index].id,
      dataUtilComm.paperData!.collectId,
    );

    // 监听方法
    _eventShowJx = eventBus.on<EventQuestionShowJx>().listen((event) {
      if (event.index == _dtk.index) {
        setState(() {});
      }
    });
    _eventOnZTDX = eventBus.on<EventQuestionOnZTDX>().listen((event) {
      setState(() {});
    });
    _eventQk = eventBus.on<EventQuestionQk>().listen((event) {
      _qkDtk();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventShowJx.cancel();
    _eventOnZTDX.cancel();
    _eventQk.cancel();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    _context = context;
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 30),
      decoration: BoxDecoration(
        color: getColorWhite1b12(szYjms: szUtilComm.szInfo.yjms),
      ),
      child: _futureData(),
    );
  }

  /// 加载数据方法
  _futureData() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
        BuildContext context,
        AsyncSnapshot<Map<String, dynamic>> snapshot,
      ) {
        if (snapshot.connectionState == ConnectionState.done) {
          debugPrint("stemPage 页面 -> futureData 加载 ===> $_init");
          if (_init) {
            Map<String, dynamic> map = snapshot.data!;
            if (!map["suc"]) {
              // 加载失败
              if (map["msg"] != "") {
                WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                  ToastUtil.show(context: _context, msg: map["msg"]);
                });
              }
              return Container(
                color: getColorWhite1b12(szYjms: szUtilComm.szInfo.yjms),
              );
            }
            _dataModel = map["data"];
            _loadData();
            _init = false;
          }
          _decryptionAnswer();
          return _content();
        } else {
          // 加载中
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 解密答案方法
  _decryptionAnswer() {
    if (widget.type == QuestionTypeEnum.memory && _dataModel.answer.isEmpty) {
      CtEnum rType = dataUtilComm.paperData!.rType;
      if (rType == CtEnum.chapter ||
          rType == CtEnum.paperRecordChapterPractice) {
        if (_dataModel.answerBase64 != null) {
          try {
            UserInfoModel model = getUserInfo();
            String answerStr = EncryptUtil.aesAnswer(
              userId: model.id,
              collectId: dataUtilComm.paperData!.id,
              answerBase64: _dataModel.answerBase64!,
            );
            var ans = jsonDecode(answerStr);
            _dataModel.answer = MyUtil.getUserAnsList(ans, _dataModel.type);
          } catch (e) {
            debugPrint("stemPage 页面 -> 解析答案发生异常 ===> $e");
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: "解析答案发生错误，请重试");
            });
          }
        }
      }
    }
  }

  /// 加载数据方法
  _loadData() {
    debugPrint("stemPage 页面 -> 加载数据方法执行 ===> ");
    dataUtilComm.paperData!.dtkList[widget.index].sign = _dataModel.sign;
    dataUtilComm.paperData!.dtkList[widget.index].st = _dataModel.stem;
    dataUtilComm.paperData!.dtkList[widget.index].answerBase64 =
        _dataModel.answerBase64;
    CtEnum rType = dataUtilComm.paperData!.rType;
    if (rType == CtEnum.everyday) {
      // 处理每日一练的答案
      if (_dataModel.record != null) {
        _selectedList = MyUtil.getUserAnsList(
          _dataModel.record!.as,
          _dataModel.type,
        );
        AnswerTypeEnum ans = _dataModel.record!.rt!
            ? AnswerTypeEnum.success
            : AnswerTypeEnum.error;
        CollectTypeEnum cType = CollectTypeEnum.def;
        if (_dataModel.collect != null && _dataModel.collect!) {
          cType = CollectTypeEnum.suc;
        }
        dataUtilComm.paperData!.dtkList[widget.index].userAns = _selectedList;
        dataUtilComm.paperData!.dtkList[widget.index].ansType = ans;
        dataUtilComm.paperData!.dtkList[widget.index].collType = cType;
      }
      // 处理每日一练的题型问题
      if (_dtk.type != _dataModel.type) {
        _dtk.type = _dataModel.type;
        dataUtilComm.paperData!.dtkList[widget.index].type = _dataModel.type;
        // 处理对应大题型的题型问题
        List<BogInfoModel> bogDtkList = dataUtilComm.paperData!.bogDtkList;
        BogInfoModel? bogInfoModel;
        int start = 0;
        int bogIndex = 0;
        for (int i = 0; i < bogDtkList.length; i++) {
          BogInfoModel model = bogDtkList[i];
          int end = start + model.total;
          if (start <= widget.index && widget.index < end) {
            bogInfoModel = model;
            bogIndex = i;
            break;
          }
          start = end;
        }
        if (bogInfoModel != null && bogInfoModel.type != _dataModel.type) {
          dataUtilComm.paperData!.bogDtkList[bogIndex].type = _dataModel.type;
        }
      }
    } else {
      _selectedList = dataUtilComm.paperData!.dtkList[widget.index].userAns;
    }
  }

  /// 内容显示
  Widget _content() {
    _dtk = dataUtilComm.paperData!.dtkList[widget.index];
    bool showOpt = _getShowOpt();
    bool showBtn = _getShowBtn();
    bool showDa = widget.type == QuestionTypeEnum.answer
        ? _dtk.ansType != AnswerTypeEnum.notDone
        : true;
    bool showJx = widget.type == QuestionTypeEnum.answer ? _dtk.showJx : true;
    bool showBj = _getShowBj(showDa);
    return MediaQuery.removePadding(
      removeTop: true,
      context: _context,
      child: ListView(
        children: [
          hiSpace(height: 24),
          _titleItem(),
          hiSpace(height: 26),
          _stemItem(),
          hiSpace(height: 40),
          if (showOpt) _optionItem(),
          if (!showOpt) _textItem(),
          if (showBtn) hiSpace(height: 40),
          if (showBtn) _btnItem(),
          if (showDa) hiSpace(height: 75),
          if (showDa) _answerItem(),
          if (showJx) hiSpace(height: 60),
          if (showJx) _analysisItem(),
          if (showBj) hiSpace(height: 60),
          if (showBj) _nodeItem(),
          hiSpace(height: 28),
        ],
      ),
    );
  }

  /// 是否显示按钮
  bool _getShowBtn() {
    bool show = false;
    if (widget.type == QuestionTypeEnum.answer) {
      if (MyUtil.getDXXZT(_dtk.type) ||
          MyUtil.getTKT(_dtk.type) ||
          MyUtil.getWDT(_dtk.type) ||
          MyUtil.getBDXXZT(_dtk.type)) {
        show = _dtk.ansType == AnswerTypeEnum.notDone;
      }
    }
    return show;
  }

  /// 是否显示选项
  bool _getShowOpt() {
    bool show = true;
    if (MyUtil.getTKT(_dtk.type) || MyUtil.getWDT(_dtk.type)) {
      show = false;
    }
    return show;
  }

  /// 是否显示笔记
  bool _getShowBj(bool showDa) {
    bool show = showDa;
    if (dataUtilComm.paperData!.rType == CtEnum.everyday) {
      show = false;
    }
    return show;
  }

  /// 添加内边距
  _showPadding(Widget childV) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: childV,
    );
  }

  /// 题型收藏显示
  _titleItem() {
    return _showPadding(
      StemTitleWidget(
        index: widget.index,
        type: widget.type,
      ),
    );
  }

  /// 题干显示
  _stemItem() {
    String tg = _dataModel.getStemStr();
    return _showPadding(
      StemRichTextWidget(
        text: tg,
      ),
    );
  }

  /// 选项显示
  _optionItem() {
    return _showPadding(
      StemOptionWidget(
        optionList: _dataModel.optionList,
        showDa: _dtk.ansType != AnswerTypeEnum.notDone,
        selectedChanged: _onTapFunXx,
        selectedList: _selectedList,
        type: widget.type,
        answer: _dataModel.answer,
        qType: _dtk.type,
      ),
    );
  }

  /// 选项反应方法-选项被点击选择时
  _onTapFunXx(String optionV) {
    debugPrint("stemPage 页面 -> 选中返回值为 ===> $optionV");
    // 判断题型
    if (MyUtil.getDXT(_dtk.type) || MyUtil.getPDT(_dtk.type)) {
      _selectedList = [optionV];
      _answerJudgment();
    } else if (MyUtil.getDXXZT(_dtk.type) || MyUtil.getBDXXZT(_dtk.type)) {
      // 判断是否选中
      bool sel = _selectedList.contains(optionV);
      if (sel) {
        // 选中
        _selectedList.remove(optionV);
      } else {
        // 未选中
        _selectedList.add(optionV);
      }
      setState(() {});
    }
  }

  /// 输入框显示方法
  _textItem() {
    return _showPadding(
      StemTextWidget(
        answer: _dataModel.answer,
        qType: _dtk.type,
        showDa: _dtk.ansType != AnswerTypeEnum.notDone,
        qId: _dtk.id,
        onTapFunQd: _textJudgment,
        type: widget.type,
        opList: _dataModel.optionList,
        ansChange: true,
      ),
    );
  }

  /// 确定按钮
  _btnItem() {
    return Center(
      child: GestureDetector(
        onTap: _onTapFunQd,
        child: Container(
          width: 1.sw-65,
          // height: 80,
          padding: EdgeInsets.only(top: 5,bottom: 8),
          decoration: BoxDecoration(
            color: getColorBlue1(szYjms: szUtilComm.szInfo.yjms),
            borderRadius: BorderRadius.circular(40),
          ),
          child: Center(
            child: Text(
              "确定",
              style: FontUtil.fontWhile1(22, fontWeight: FontWeight.w500),
            ),
          ),
        ),
      ),
    );
  }

  /// 确定按钮点击方法
  _onTapFunQd() {
    if (MyUtil.getDXXZT(_dtk.type) || MyUtil.getBDXXZT(_dtk.type)) {
      _answerJudgment();
    } else {
      eventBus.fire(EventQuestionOnOpt(qId: _dtk.id));
    }
  }

  /// 填空问答题判断
  _textJudgment(bool change, List<String> list) {
    // 获取填入数据
    _selectedList = list;
    _answerJudgment();
  }

  /// 答案判断是否正确，
  _answerJudgment() {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    DataModel data = dataUtilComm.dataModel;
    // 用户答案
    String ans = MyUtil.getUserAnsStr(_selectedList, _dataModel.type);
    String rightAnswer = jsonEncode(_dataModel.answer);
    if (MyUtil.getDXT(_dataModel.type) || MyUtil.getPDT(_dataModel.type)) {
      if (_dataModel.answer.isNotEmpty) {
        rightAnswer = _dataModel.answer[0];
      }
    }

    // 传入后端，判断是否正确，
    SubjectDao.pushQuestionRightCheck(
      industryCode: data.industryId,
      examId: data.examId,
      categoryId: data.categoryId,
      collectId: dataUtilComm.paperData!.id,
      qid: _dtk.id,
      typeEnum: _dataModel.type,
      as: ans,
      answer: _dataModel.answerBase64,
      clientRightAnswer: rightAnswer,
    ).then((RecordModel value) {
      ToastUtil.loadingBoxRemove();
      _dataModel.answer = MyUtil.getUserAnsList(value.as!, _dataModel.type);
      _dtk.ansType = value.rt! ? AnswerTypeEnum.success : AnswerTypeEnum.error;
      dataUtilComm.paperData!.dtkList[widget.index].ansType = _dtk.ansType;
      dataUtilComm.paperData!.dtkList[widget.index].userAns = _selectedList;
      dataUtilComm.paperData!.dtkList[widget.index].ansDate =
          DateTime.now().millisecondsSinceEpoch;
      dataUtilComm.paperData!.dc++;
      if (_dtk.ansType == AnswerTypeEnum.error) {
        dataUtilComm.paperData!.ec++;
      }
      // 答题成功默认显示解析
      dataUtilComm.paperData!.dtkList[widget.index].showJx = true;
      eventBus.fire(EventQuestionDtShowJx(index: widget.index));
      _dtkJudgment();
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();
      if (MyUtil.getDXT(_dataModel.type)) {
        _selectedList = [];
      }
      String msg = "未知错误，请重试";
      if (e is DaoException) {
        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    });
  }

  /// 答案处理
  _dtkJudgment() {
    // 本页面刷新
    setState(() {});
    // 判断是否答对自动跳转下一题
    if (szUtilComm.szInfo.zdtz && _dtk.ansType == AnswerTypeEnum.success) {
      eventBus.fire(EventQuestionOnDtk(index: _dtk.index + 1));
    }
  }

  /// 答案组件
  _answerItem() {
    // 判断是否显示你选择的
    bool showSel = widget.type == QuestionTypeEnum.answer
        ? _selectedList.isNotEmpty
        : false;
    return StemAnswerWidget(
      ans: _dataModel.answer,
      sel: _selectedList,
      suc: _dtk.ansType == AnswerTypeEnum.success,
      showSel: showSel,
      qType: _dtk.type,
      doingNumber: _dataModel.doingNumber,
      errorNumber: _dataModel.errorNumber,
    );
  }

  /// 显示解析组件
  _analysisItem() {
    String text = _dataModel.analysis;
    if (text.isEmpty) {
      text = "暂无";
    }
    return StemAnalysisWidget(
      ana: text,
    );
  }

  /// 笔记组件显示
  _nodeItem() {
    PaperDataModel paperData = dataUtilComm.paperData!;
    return StemNoteWidget(
      qId: _dataModel.id,
      relationId: paperData.collectId,
      relationName: paperData.name,
      stem: _dtk.st!,
      type: MyUtil.getCollTypeEnum(paperData.rType),
    );
  }

  /// 清空做题数据
  void _qkDtk() {
    _dtk.ansType = AnswerTypeEnum.notDone;
    _dtk.ansDate = null;
    _dtk.showJx = false;
    _dtk.userAns = [];
    _selectedList = [];
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;
}
